<!-- 组件说明 -->
<template>
  <div class="walletWrap">
    <goback
        :title="'WALLET'"
        :rightTop="rightTop"
        :ifTransparent="false"
    ></goback>
    <div class="container clearfix">
      <div class="top">
        <p>My balance</p>
        <div class="list">
          <div class="li">
            <div class="left">
              <img :src="huangzuan" alt=""/>
              <p>Crown points</p>
            </div>
            <span>{{ pageData.integraliOne }}</span>
          </div>
          <div class="li">
            <div class="left">
              <img :src="lanzuan" alt=""/>
              <p>Blue diamond points</p>
            </div>
            <span>{{ pageData.integraliTwo }}</span>
          </div>
          <div class="li">
            <div class="left">
              <img :src="star" alt=""/>
              <p>Cash back points</p>
            </div>
            <span>{{ pageData.cashBackIntegral }}</span>
          </div>
          <div class="li">
            <!--          <div class="li last2">-->
            <div class="left">
              <img :src="duihuan" alt=""/>
              <p>Cash available</p>
            </div>
            <span>
              {{ pageData.waitExchangeAmount }}
            </span>
          </div>
          <div class="li last3">
            <span>Withdrawal Rule</span>
            <img :src="askPic" @click="goto('txRulers')">
          </div>
        </div>
      </div>
      <div class="tips" v-if="false">
        <div class="line1">
          Withdraw <br/>
          <span>(Minimum Extract {{ pageData.withdrawMinIntegral }},</span>
          <span>Minimum Extract {{ pageData.withdrawManIntegral }})</span>
        </div>
        <div class="line2">
          <span>Withdrawal Weight: </span>{{ currentWeight }}‰
        </div>
      </div>
      <div class="withdrawNumWrap">
        <div class="underline">
          <input
              :autofocus="
              Number(pageData.withdrawManIntegral)>0 &&
                pageData.todayWithdrawCount == 0
            "
              type="number"
              v-model.trim="withdrawIntegral"
              :class="withdrawIntegralWarning ? 'redColor' : ''"
              placeholder="Enter the Withdrawal amount of money"
          />
        </div>
        <span class="fee">₹ {{ fee }}</span>
      </div>
      <div class="withdrawMethodWrap">
        <!--        <p>Withdrawal method</p>-->
        <div class="methodList">
          <div class="li">
            <div class="left">
<!--              <img :src="" alt=""/>-->
              <p style="padding-left: 0">Withdrawal account information</p>
            </div>
          </div>
        </div>
        <div class="currentMethodUserList">
          <div class="li" v-for="(item, index) in accountList" :key="index">
            <div class="top">
              <p>{{ item.userName }}</p>
              <img
                  v-if="index == selectedAccountIndex"
                  class="selectStatus"
                  :src="selected"
                  alt=""
              />
              <img
                  @click="historyAccountSelect(index, item)"
                  v-else
                  class="selectStatus"
                  :src="noselect"
                  alt=""
              />
            </div>
            <div class="Number underline">{{ item.bankName }}</div>
            <div class="Number underline">{{ item.bankAccount }}</div>
            <div class="Number underline">{{ item.bankIfsc }}</div>
            <div class="Number underline">{{ item.mobile }}</div>
            <div class="Number underline">{{ item.email }}</div>
          </div>
        </div>
        <div class="addBtnWrap" v-if="!ifKeepNewAccountShow">
          <p @click="newAccountBtnFn">Add</p>
        </div>
        <div class="addContainerWrap" v-if="ifKeepNewAccountShow">
          <div class="top">
            <p>Keep adding</p>
            <img class="selectStatus" :src="selected" alt=""/>
          </div>
          <div class="add1 underline">
            <input
                v-model="newAccountName"
                type="text"
                placeholder="Enter your real user name"
            />
          </div>
          <div class="add2 underline">
            <input
                v-model="newAccountbankname"
                type="text"
                placeholder="Enter your bank name"
            />
          </div>
          <div class="add2 underline">
            <input
                v-model="newAccountNo"
                type="text"
                placeholder="Enter your bank account"
            />
          </div>
          <div class="add2 underline">
            <input
                v-model="newAccountbankIFSC"
                type="text"
                placeholder="Enter your bank IFSC"
            />
          </div>
          <div class="add2 underline">
            <input
                v-model="newAccountPhoneNumber"
                type="text"
                placeholder="Enter your Phone number"
            />
          </div>
          <div class="add2 underline">
            <input
                v-model="newAccountEmail"
                type="text"
                placeholder="Enter your Email"
            />
          </div>
        </div>
      </div>
    </div>
    <div
        @click="openGetPhoneCode"
        class="widthdrawBtn"
        v-if="withdrawIntegral > Number(this.pageData.withdrawMinIntegral) &&
          withdrawIntegral <= Number(this.pageData.withdrawManIntegral) &&
          pageData.todayWithdrawCount == 0&&
          ajaxAccountData.accountName &&
          ajaxAccountData.accountNo &&
          ajaxAccountData.bankName &&
          ajaxAccountData.bankIfsc &&
          ajaxAccountData.email &&
          ajaxAccountData.mobile">
      WITHDRAW
    </div>
    <div @click="openGetPhoneCodeTips" class="widthdrawBtn" v-else>WITHDRAW</div>

    <van-overlay :show="overlayShow" @click.stop="fnstop">
      <div class="overlayWrapper" @click.stop>
        <div class="detail">
          <div class="detail2">
            <p>Phone verification</p>
            <div class="underline phone">
              Phone Number : ***{{ phoneShow() }}
            </div>
            <div class="underline phoneCode">
              <input type="number" v-model.trim="verificationCode"/>
              <div class="right">
                <span></span>

                <p class="tips" v-if="lastTime != initLastTime">
                  {{ lastTime + " S" }}
                </p>
                <p
                    class="tips tipsBtn"
                    @click.stop="resendFn"
                    v-if="lastTime == initLastTime"
                >
                  Resend
                </p>
              </div>
            </div>
          </div>
          <div class="btns">
            <p class="cancel" @click="cancelSubmit">CANCEL</p>
            <p
                :class="verificationCode ? 'submit canDo' : 'submit'"
                @click="doSubmit"
            >
              SUBMIT
            </p>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import {ifLogin, utilGotoLogin} from "@/utils/index.js";
import {mapState} from "vuex";

export default {
  components: {},
  name: "percenterWallet",
  data() {
    return {
      duihuan: require("@/assets/imgNews/percenter/wallet/duihuan.png"),
      huangzuan: require("@/assets/imgNews/index/righttop-left.png"),
      lanzuan: require("@/assets/imgNews/index/righttop-left-zuan.png"),
      star: require("@/assets/imgNews/percenter/wallet/star.png"),
      noselect: require("@/assets/imgNews/percenter/wallet/noselect.png"),
      selected: require("@/assets/imgNews/percenter/wallet/selected.png"),
      // : require("@/assets/imgNews/percenter/wallet/.png"),
      askPic: require("@/assets/imgNews/index/pros1.png"),

      accountList: [],
      pageData: {},
      selectedAccountIndex: -1,
      ifKeepNewAccountShow: false,
      ifKeepNewAccount: true,
      newAccountName: "",//用户名
      newAccountNo: "",//账号
      newAccountbankname: "",//账号
      newAccountbankIFSC: "",//账号
      newAccountPhoneNumber: "",//手机号
      newAccountEmail: "",//邮箱

      rightTop: {
        title: "RECORD",
        name: "percenterWalletRecord"
      },
      WithdrawalWeight: 5,
      withdrawIntegral: "", //提现金额
      overlayShow: false, //获取验证码弹窗-默认不显示
      lastTime: 0,
      initLastTime: 60,
      verificationCode: "",
      withdrawIntegralWarning: false
    };
  },
  watch: {
    withdrawIntegral(newVal, oldVal) {
      if (newVal && !/^\+?[1-9]\d*$/.test(newVal)) {
        this.$notify({
          type: "warning",
          message: "Please enter integers greater than 0"
        });
        this.withdrawIntegral = "";
      }
      if (
          newVal < Number(this.pageData.withdrawMinIntegral) ||
          newVal > Number(this.pageData.withdrawManIntegral)
      ) {
        this.withdrawIntegralWarning = true;
      } else {
        this.withdrawIntegralWarning = false;
      }
    }
  },
  computed: mapState({
    // 箭头函数可使代码更简练
    userStoreData: state => state.user,

    currentWeight() {
      let resultData = "0.00";
      if (this.pageData && this.pageData.weight) {
        resultData = (Number(this.pageData.weight) * 1000).toFixed(2);
      }
      return resultData;
    },

    fee() {
      let resultData = "0.00";
      if (this.withdrawIntegral) {
        resultData =
            Math.floor(
                Number(Number(this.withdrawIntegral) *(1-this.pageData.deductWeight))
            );
        if (resultData == 0) {
          resultData = "0.00";
        }
      }
      return resultData;
    },
    ajaxAccountData() {
      let initData = {
        accountName: "",
        accountNo: "",
        bankName: "",
        bankIfsc: "",
        email: "",
        mobile: ""
      };
      if (this.selectedAccountIndex != -1) {
        initData = {
          accountName: this.accountList[this.selectedAccountIndex].userName,
          accountNo: this.accountList[this.selectedAccountIndex].bankAccount,
          bankName: this.accountList[this.selectedAccountIndex].bankName,
          bankIfsc: this.accountList[this.selectedAccountIndex].bankIfsc,
          email: this.accountList[this.selectedAccountIndex].email,
          mobile: this.accountList[this.selectedAccountIndex].mobile,
        };
      } else {
        initData = {
          accountName: this.newAccountName,
          accountNo: this.newAccountNo,
          bankName: this.newAccountbankname,
          bankIfsc: this.newAccountbankIFSC,
          email: this.newAccountEmail,
          mobile: this.newAccountPhoneNumber,
        };
      }
      return initData;
    }
  }),
  methods: {
    cancelSubmit() {
      this.overlayShow = false;
    },
    doSubmit() {
      let zs = this;
      this.$toast.loading({
        message: "waiting",
        duration: 0,
        forbidClick: true
      });
      zs.api.userController
          .userApplyWithdraw({
            accountName: zs.ajaxAccountData.accountName,
            bankNo: zs.ajaxAccountData.accountNo,
            bankName: zs.ajaxAccountData.bankName,
            bankIfsc: zs.ajaxAccountData.bankIfsc,
            email: zs.ajaxAccountData.email,
            mobile: zs.ajaxAccountData.mobile ,
            userId: zs.userStoreData.userId,
            verificationCode: this.verificationCode,
            withdrawAccountType: 1, // 1 pyytm
            withdrawIntegral: this.withdrawIntegral
          })
          .then(res => {
            console.log(res);
            if (res.data.code === 200) {
              zs.$toast("Withdraw SUCCESS");
              zs.$router.replace({
                name: "purseindex"
              });
            } else {
              zs.$toast(res.data.info ? res.data.info : "please try again later");
              // this.lastShow(); // TODO: 待续
            }
          });
    },
    resendFn() {
      let zs = this;
      this.$toast.loading({
        message: "waiting",
        duration: 0,
        forbidClick: true
      });
      zs.api.userController
          .userObatinRegistersms({
            phone: zs.userStoreData.phone
          })
          .then(res => {
            console.log(res);
            if (res.data.code === 200) {
              zs.$toast("send code SUCCESS");
              this.lastShow();
            } else {
              zs.$toast(res.data.info);
              // this.lastShow(); // TODO: 待续
            }
          });
    },
    // 验证码
    lastShow() {
      clearInterval(this.timeInterval);
      this.timeInterval = setInterval(() => {
        if (this.lastTime > 0) {
          this.lastTime--;
        } else {
          clearInterval(this.timeInterval);
          this.lastTime = this.initLastTime;
        }
      }, 1000);
    },
    phoneShow() {
      let phone = this.userStoreData.phone;
      return phone.substring(phone.length - 3);
    },
    // 打开验证码窗口
    openGetPhoneCode() {
      let zs = this;
      if (this.withdrawIntegralWarning) {
        this.$notify({
          type: "warning",
          message:
              "Withdrawals must be between " +
              zs.pageData.withdrawMinIntegral +
              " and " +
              zs.pageData.withdrawManIntegral
        });
        return;
      }
      zs.api.userController
          .userObatinRegistersmsSurplustime({
            phone: zs.userStoreData.phone
          })
          .then(res => {
            console.log(res);
            if (res.data.code === 200) {
              if (res.data.data == 0) {
                this.lastTime = this.initLastTime;
                this.overlayShow = true;
                this.resendFn();
              } else {
                zs.$toast({
                  message: "Wait " + res.data.data + " S to try again!"
                });
              }
            } else {
              zs.$toast(res.data.info);
            }
          });
    },
    openGetPhoneCodeTips(){
      let zs = this;
      zs.$toast({
        message: "Cash availabel must be more than 100 when you want to withdrawal and You can only withdraw once a day",
        duration:4000,
      });
    },
    // 点击add 新加按钮事件
    newAccountBtnFn() {
      this.ifKeepNewAccountShow = true;
      this.selectedAccountIndex = -1;
    },
    // 历史账号选择点击事件
    historyAccountSelect(index, item) {
      console.log(item);
      this.selectedAccountIndex = index;
      this.ifKeepNewAccount = false;
      this.ifKeepNewAccountShow = false;
      this.newAccountName = "";
      this.newAccountNo = "";
      this.newAccountbankname = "";
      this.newAccountbankIFSC = "";
      this.newAccountPhoneNumber = "";
      this.newAccountEmail = "";
    },
    userUpdateUserinfoFn(type) {
      this.$toast.loading({
        duration: 0,
        forbidClick: true
      });
      this.api.userController
          .userUpdateUserinfo({
            age: type === "age" ? this.ageVal : this.userStoreData.age,
            avatar:
                type === "avatar" ? this.uploadpicUrl : this.userStoreData.avatar,
            nickName:
                type === "nickName"
                    ? this.nickNameIVal
                    : this.userStoreData.nickName,
            sex: type === "sex" ? this.sexVal : this.userStoreData.sex,
            phone: this.userStoreData.phone,
            userId: this.userStoreData.userId
          })
          .then(res => {
            this.$toast.clear();
            if (res.data.code == 200) {
              this.$store.dispatch("syncUserInfo").then(() => {
                console.log(this.$store.state);
                setTimeout(() => {
                  this.userStoreDataShow();
                  this.initShow();
                  this.$forceUpdate();
                }, 0);
              });
            }
          });
    },
    ifLoginFn() {
      return ifLogin();
    },
    headerClickFn() {
    },
    gotoLogin() {
      utilGotoLogin();
    },
    contentFn(title) {
      if (!ifLogin()) {
        utilGotoLogin();
      } else {
        console.log(title);
        this.initShow(); //隐藏所有弹窗
        if (title === "Nickname") {
          this.nickNameIptIfShow = true;
        } else if (title === "Age") {
          this.ageValIfShow = true;
        } else if (title === "Gender") {
          this.sexValIfShow = true;
        }
      }
    },
    pageinit() {
      this.getPageInfo();
      this.getAccountList();
    },
    getPageInfo() {
      this.$toast.loading({
        duration: 0,
        forbidClick: true
      });
      this.api.userController
          .userObtainWthdrawinfo({
            userId: this.userStoreData.userId
          })
          .then(res => {
            this.$toast.clear();
            if (res.data.code == 200) {
              this.pageData = res.data.data;
            }
          });
    },
    getAccountList() {
      this.$toast.loading({
        duration: 0,
        forbidClick: true
      });
      this.api.userController
          .userObtainWthdrawaccount({
            userId: this.userStoreData.userId,
            type: 1
          })
          .then(res => {
            this.$toast.clear();
            if (res.data.code == 200) {
              this.accountList = res.data.data;
            }
          });
    },
    // 路有跳转
    goto(name) {
      this.$router.push({
        name
      });
    },
    fnstop() {
      return false;
    }
  },
  mounted() {
    this.pageinit();
  },
  beforeCreate() {
  }, //生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="less" scoped>
@import url("./../../../assets/css/common.less");
@import url("./percenter-wallet.less");
</style>
